package tuiLayer;
import ControlLayer.*;
import java.util.Scanner;
import ModelLayer.*;
/**
 * Write a description of class LoanUI here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class LoanUI
{
    private LoanCtr loanCtr;
    private String command;

    public LoanUI()
    {
        loanCtr = new LoanCtr();
    }

    public void start()
    {
        boolean finished = false;
        while (!finished)
        {
            printMenu();
            reader();
            if(command.equals("1"))
            {
                System.out.println("Returning to main menu.");
                finished = true;
            }
            else if(command.equals("help"))
            ;
            else if(command.equals("2"))
                create();
            else if(command.equals("3"))
                getLoan();
            else if(command.equals("4"))
                returnLoan();
            else if(command.equals("5"))
                listLoans();
        }
    }

    private void reader()
    {
        final String[] validCommands = {"1","2","3","4","5","help",};
        Scanner reader;
        reader = new Scanner(System.in);
        boolean finished = false;
        while(!finished)
        {
            System.out.println();
            System.out.print("> ");
            String terminal = reader.nextLine();
            System.out.println();
            for(int i = 0; i < validCommands.length; i++) 
            {
                if(validCommands[i].equals(terminal))
                {
                    command = terminal;
                    finished = true;
                }
            }
            if(finished == false)
                System.out.print("Please try again.");
        }
    }

    private String reader2()
    {
        Scanner terminal = new Scanner(System.in);
        System.out.print(">> ");
        String command2 = terminal.nextLine();
        return command2;
    }

    private void printMenu()
    {
        System.out.println();
        System.out.println("*** Loan Menu ***");
        System.out.println("(1) Return to main menu.");
        System.out.println("(2) Create new loan.");
        System.out.println("(3) Show information about specific loan.");
        System.out.println("(4) Return loan.");
        System.out.println("(5) Show all loans.");
        System.out.println("Please select using the keypad");
    }

    private void create()
    {
        System.out.println("Type in the DVD's title:");
        String titleSearch = reader2();
        DvdCtr d = new DvdCtr();
        if(d.findDvd(titleSearch) != null)
        {
            System.out.println("Type in the person's name:");
            String personSearch = reader2();
            PersonCtr p = new PersonCtr();
            if(p.findPerson(personSearch) != null)
            {
                System.out.println("Avaliable copies:");
                d.printCopyList(titleSearch);
                System.out.println("Type in the copy's serial number:");
                String serialNumberSearch = reader2();
                if(d.findCopy(serialNumberSearch, titleSearch) != null)
                {
                    System.out.println("Type in:");
                    System.out.println("id");
                    String id = reader2();
                    String borrowDate = null;
                    System.out.println("borrow date");
                    System.out.println("Format: 00/00/0000");
                    borrowDate = reader2();
                    dateFormat(borrowDate);
                    while(dateFormat(borrowDate) == null)
                    {
                        System.out.println("Wrong format!");
                        System.out.println("Try again!");
                        System.out.println("borrow date");
                        System.out.println("Format: 00/00/0000");
                        borrowDate = reader2();
                        dateFormat(borrowDate);
                    }
                    System.out.println("period");
                    String period = reader2();
                    String purchaseDate = d.findCopy(serialNumberSearch, titleSearch).getPurchaseDate();
                    String purchasePrice = d.findCopy(serialNumberSearch, titleSearch).getPurchasePrice();
                    loanCtr.createLoan(id,borrowDate,period,serialNumberSearch,purchaseDate,purchasePrice,personSearch,titleSearch);                    
                    d.removeCopy(serialNumberSearch, titleSearch);
                    System.out.println("* The loan has just been created *");
                }
                else
                {
                    System.out.println("Copy not found.");
                }
            }
            else
            {
                System.out.println("Person not found.");
            }
        }
        else
        {
            System.out.println("DVD not found.");
        }
    }

    private void getLoan()
    {
        System.out.println("Type in the loan's id:");
        String id = reader2();
        if(loanCtr.findLoan(id) !=null)
        {
            System.out.println();
            System.out.println("id: " +loanCtr.getId(id)+ ".");
            System.out.println("name: " +loanCtr.getName(id)+ ".");
            System.out.println("borrow date: " +loanCtr.getBorrowDate(id)+ ".");
            System.out.println("return date: " +loanCtr.getReturnDate(id)+ ".");
            System.out.println("period: " +loanCtr.getPeriod(id)+ ".");
            System.out.println("state: " +loanCtr.getState(id)+ ".");
        }
        else
        {
            System.out.println("Loan not found.");
        }
    }

    private void returnLoan()
    {
        System.out.println("Type in the loan's id:");
        String id = reader2();
        if(loanCtr.findLoan(id) != null)
        {
            System.out.println("type in the return date");
            System.out.println("Format: 00/00/0000");
            String date = null;
            date = reader2();
            dateFormat(date);
            while(dateFormat(date) == null)
            {
                System.out.println("Wrong format!");
                System.out.println("Try again!");
                System.out.println("type in the return date");
                System.out.println("Format: 00/00/0000");
                date = reader2();
                dateFormat(date);
            }
            loanCtr.findLoan(id).setReturnDate(date);
            String a = loanCtr.findLoan(id).getBorrowDate().substring(6,10);
            int b = Integer.parseInt(a);
            String c = loanCtr.findLoan(id).getReturnDate().substring(6,10);
            int d = Integer.parseInt(c);
            String e = loanCtr.findLoan(id).getBorrowDate().substring(3,5);
            int f = Integer.parseInt(e);
            String g = loanCtr.findLoan(id).getReturnDate().substring(3,5);
            int h = Integer.parseInt(g);
            String j = loanCtr.findLoan(id).getBorrowDate().substring(0,2);
            int k = Integer.parseInt(j);
            String l = loanCtr.findLoan(id).getReturnDate().substring(0,2);
            int m = Integer.parseInt(l);
            int n = 0;
            int p = 0;
            int q = 0;
            n = (d - b) * 365;
            double o = ((h - f) * 365) / 12;
            p = (int) o + 1;
            q = m - k;
            int r = n + p + q;
            String s = loanCtr.findLoan(id).getPeriod();
            int t = Integer.parseInt(s);
            if(t >= r)
            {
                String serialNumber = loanCtr.findLoan(id).getSerialNumber();
                String purchaseDate = loanCtr.findLoan(id).getPurchaseDate();
                String purchasePrice = loanCtr.findLoan(id).getPurchasePrice();
                String title = loanCtr.getTitle(id);
                DvdCtr u = new DvdCtr();
                u.findDvd(title).createCopy(serialNumber, purchaseDate, purchasePrice);
                String state = "Returned in time";
                loanCtr.findLoan(id).setState(state);
                System.out.println("The DVD has been returned in time.");
            }
            else
            {
                int overDueDays = r - t;
                String serialNumber = loanCtr.findLoan(id).getSerialNumber();
                String purchaseDate = loanCtr.findLoan(id).getPurchaseDate();
                String purchasePrice = loanCtr.findLoan(id).getPurchasePrice();
                String title = loanCtr.getTitle(id);
                DvdCtr u = new DvdCtr();
                u.findDvd(title).createCopy(serialNumber, purchaseDate, purchasePrice);
                String state2 = "" + Integer.toString(overDueDays) + " days overdue";
                loanCtr.findLoan(id).setState(state2);
                System.out.println("The DVD has been returned.");
                System.out.println("The loan period of this DVD expired " + overDueDays + " days ago. ");
            }
        }
        else
        {
            System.out.println("Loan not found.");
        }
    }

    private void listLoans()
    {
        System.out.println("\f");

        for (Loan loanObj: loanCtr.getList())
        {
            System.out.println("--------------------------");
            System.out.println("Id: " + loanObj.getId());
            System.out.println("Name: " + loanObj.getName());
            System.out.println("Title: " + loanObj.getTitle());
            System.out.println("Borrow date: " + loanObj.getBorrowDate());
            System.out.println("Return date: " + loanObj.getReturnDate());
            System.out.println("Period: " + loanObj.getPeriod());
            System.out.println("Serial number: " + loanObj.getSerialNumber());
            System.out.println("Purchase date: " + loanObj.getPurchaseDate());
            System.out.println("Purchase price: " + loanObj.getPurchasePrice());
            System.out.println("--------------------------");
        }
    }

    private String dateFormat(String date)
    {
        String borrowDate = date;
        String[] days = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"};
        String[] months = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"};
        String goodFormat = null;
        if(borrowDate.length() < 9)
        {
            return goodFormat;
        }
        else
        {
            for(int i = 0; i < days.length; i++)
            {
                if(days[i].equals(borrowDate.substring(0, 2)))
                {
                    for(int i2 = 0; i2 < months.length; i2++)
                    {
                        if(months[i2].equals(borrowDate.substring(3, 5)))
                        {
                            if(parseInt(borrowDate.substring(6,10), 0) > 1900 && parseInt(borrowDate.substring(6,10), 0) < 2999)
                            {
                                goodFormat = borrowDate;
                            }
                            else
                            {
                                goodFormat = null;
                            }
                        }
                    }
                }
            }
        }
        return goodFormat;
    }

    private static int parseInt(String year, int valueIfInvalid)
    {
        try {
            if (year == null) 
            {
                return valueIfInvalid;
            }
            else 
            {
                return Integer.parseInt(year);
            }
        } 
        catch (final NumberFormatException ex) 
        {
            return valueIfInvalid;
        }
    }
}